<script>
// 对比分析
import { mapGetters, mapMutations } from 'vuex';
export default {
  name: 'Analys',
  props: {
    mapData: {
      type: Array,
      default: () => [],
    },
    options: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      layerData1: [],
      layerData2: [],
      layerParams1: [],
      layerParams2: [],
      analysType: [{ value: 'differ', label: '相交' }, { value: 'clip', label: '裁剪' }],
      isFirstForm: true,
      formItem: {
        layer1: '',
        params1: '',
        layer2: '',
        params2: '',
        type: 'clip',
        geometry: null,
        spaceRelation: 'intersects',
      },
      isAnalys: false,
      analysLoading: false,
      changesLoading: false,
      folwLoading: false,
      selectLayerData: {},
      analysLayerData: {},
    };
  },
  computed: {
    ...mapGetters(['controls', 'currentId']),
  },
  watch: {
    options: {
      handler(newVal, oldVal) {
        if (Object.keys(newVal).length !== 0) {
          for (let key in newVal.data) {
            if (key === 'map_1') {
              this.layerData1 = newVal.data[key];
              if (Object.keys(this.selectLayerData).length !== 0)
                this.selectLayerData[`layer${newVal.data[key][0].type}`] = newVal.data[key];
            }
            if (key === 'map_2') {
              this.layerData2 = newVal.data[key];
              if (Object.keys(this.selectLayerData).length !== 0)
                this.selectLayerData[`layer${newVal.data[key][0].type}`] = newVal.data[key];
            }
          }
          // 自动填充查询字段
          if (newVal.data && newVal.data.queryOptions && this.isFirstForm) {
            this.isFirstForm = false;
            this.formItem = Object.assign({}, this.formItem, newVal.data.queryOptions.options);
            this.layerParams1 = newVal.data.queryOptions.params.layerParams1;
            this.layerParams2 = newVal.data.queryOptions.params.layerParams2;
          }
        }
      },
      immediate: true,
    },
    formItem: {
      handler(newVal) {
        const params = {
          layerParams1: this.layerParams1,
          layerParams2: this.layerParams2,
        };
        this.updateLayerData({ options: newVal, params });
      },
      deep: true,
    },
  },
  mounted() {
    this.$events.emit('on-getmap');
  },
  beforeDestroy() {
    this.formItem = {
      layer1: '',
      params1: '',
      layer2: '',
      params2: '',
      type: 'clip',
      geometry: null,
      spaceRelation: 'intersects',
    };
  },
  methods: {
    ...mapMutations({
      updateAppOptions: 'UPDATE_CHART_CONFIG',
    }),
    // 得到所有的地图
    getMapData(type) {
      return this.mapData.filter(item => item.num === type);
    },
    // 更新应用程序配置
    updateLayerData(queryOptions) {
      if (this.$store.getters.currentId) {
        let currentControl = this.$store.getters.controls[this.$store.getters.currentId];
        currentControl.options.data = {
          ...currentControl.options.data,
          queryOptions,
        };
        this.updateAppOptions({ data: { [this.$store.getters.currentId]: currentControl } });
      }
    },
    // 图层选择
    selectLayer1(layers) {
      let layerData;
      layerData = this.layerData1.filter(item => item.name === layers);
      if (layers === '') {
        if (this.formItem.layer1 === '') {
          this.$refs.select1.query = '';
          this.$refs.select1.lastQuery = '';
          this.$refs.select1.selectedSingle = '';
          this.$refs.select1.clearSingleSelect();
        } else {
          this.$refs.select2.query = '';
          this.$refs.select2.lastQuery = '';
          this.$refs.select2.selectedSingle = '';
          this.$refs.select2.clearSingleSelect();
        }
      }
      if (layerData.length !== 0) {
        // 保存选择的两个图层信息
        this.analysLayerData[`layer${layerData[0].type}`] = layerData;
        // 字段查询
        this.layerParams1 = layerData[0].services[0].schema;
      }
    },
    // 图层选择
    selectLayer2(layers) {
      let layerData;
      layerData = this.layerData2.filter(item => item.name === layers);
      if (layers === '') {
        if (this.formItem.layer1 === '') {
          this.$refs.select1.query = '';
          this.$refs.select1.lastQuery = '';
          this.$refs.select1.selectedSingle = '';
          this.$refs.select1.clearSingleSelect();
        } else {
          this.$refs.select2.query = '';
          this.$refs.select2.lastQuery = '';
          this.$refs.select2.selectedSingle = '';
          this.$refs.select2.clearSingleSelect();
        }
      }
      if (layerData.length !== 0) {
        // 保存选择的两个图层信息
        this.analysLayerData[`layer${layerData[0].type}`] = layerData;
        // 字段查询
        this.layerParams2 = layerData[0].services[0].schema;
      }
    },
    // 选择分析方式
    selectType(type) {},
    // 叠加分析
    overLapAnalys() {
      let layers = [];
      // 清除高亮
      this.clearGeojson();
      if (this.formItem['layer1'] === '' || this.formItem['layer2'] === '') return;
      for (const key in this.formItem) {
        if (key === 'layer1' || key === 'layer2') {
          if (this.formItem.geometry) {
            layers.push({
              typename: this.formItem[key],
              filter: `${this.formItem.spaceRelation}(the_geom,${this.formItem.geometry})`,
            });
          } else {
            layers.push({ typename: this.formItem[key] });
          }
        }
      }
      // 设置查询条件
      this.analysLoading = true;
      const layerData = this.layerData1.filter(item => item.name === this.formItem['layer1']);
      const url = new URL(layerData[0].services[0].servicesurl);
      this.baseUrl = url.origin + url.pathname;
      const queryUrl = url.origin + url.pathname;
      const relCrs = url.searchParams.get('srs');
      const mapData = this.getMapData(1);
      this.mapId = mapData[0].mapId;
      this.$store
        .dispatch(`${this.mapId}/MAP_WPS_OVERLAP`, {
          url: queryUrl,
          options: {
            RELLAYERS: {
              usegrid: '1',
              optype: this.formItem.type,
              tolerance: '0.000001',
              geombuffer: '0',
              layers,
            },
          },
        })
        .then(response => {
          this.isAnalys = true;
          this.analysLoading = false;
          // 返回的crs不是真正的crs，要拿到真正的crs
          // if (typeof response !== 'string') {
          this.analysData = {
            ...JSON.parse(response),
            url: queryUrl,
            baseUrl: this.baseUrl,
            relCrs: relCrs,
          };
          if (response) {
            this.$events.emit('on-show-analys', {
              ...this.analysData,
              selectLayerData: this.analysLayerData,
              type: 'wfsQuery',
            });
          }
          // } else {
          //   this.$Message.error('叠接分析返回参数错误！');
          // }
        });
    },
    // 清除图层
    clearGeojson() {
      this.mapData.forEach(item => {
        if (this.$store.getters[`${item.mapId}/geojson`])
          this.$store.commit(`${item.mapId}/SET_MAP_GEOJSON`, { geojson: {}, type: 'once' });
      });
    },
    // 变化统计
    overLapChanges() {
      this.getAnalysData();
      // 清除高亮
      this.clearGeojson();
      this.$events.emit('on-show-analys', {
        ...this.analysData,
        type: 'overLapChanges',
        params: `${this.formItem.params1},over_${this.formItem.params2}`,
        selectLayerData: this.analysLayerData,
      });
    },
    getDrawLayer(geo) {
      if (geo) {
        const geometry = geo.toGeoJSON();
        let wktStr = L.Wkt.Wkt.prototype.fromObject(geometry.geometry, true);
        wktStr = wktStr.write();
        wktStr = wktStr.replace(/undefined/g, ' ');
        this.formItem.geometry = wktStr;
      } else {
        this.formItem.geometry = geo;
      }
    },
    // 流向分析
    flowAnalysis() {
      this.$events.emit('on-show-flow', true);
      this.getAnalysData();
      this.$events.emit('on-show-analys', {
        ...this.analysData,
        type: 'flowAnalys',
        params: `${this.formItem.params1},over_${this.formItem.params2}`,
        selectLayerData: this.analysLayerData,
      });
    },
    // 得到统计参数
    getAnalysData() {
      for (const key in this.formItem) {
        if (this.formItem[key] === '') {
          this.$Message.error('请将表单填写完整！');
          return;
        }
      }
    },
  },
};
</script>
<template>
  <div class="datav-analys">
    <Form
      ref="analysform"
      :model="formItem"
      :label-width="80"
      label-position="left">
      <FormItem
        label="图层一：">
        <Select
          ref="select1"
          v-model="formItem.layer1"
          :clearable="true"
          @on-change="selectLayer1">
          <Option
            v-for="(item,index) in layerData1"
            :value="item.name"
            :key="index">{{ item.name }}</Option>
        </Select>
      </FormItem>
      <FormItem label="图层字段：">
        <Select
          ref="select2"
          v-model="formItem.params1"
          :disabled="formItem.layer1===''?true:false"
          placeholder="请选择图层一"
        >
          <Option
            v-for="(item,index) in layerParams1"
            :value="item.name"
            :key="index">{{ item.name }}</Option>
        </Select>
      </FormItem>
      <FormItem label="图层二：">
        <Select
          v-model="formItem.layer2"
          @on-change="selectLayer2">
          <Option
            v-for="(item,index) in layerData2"
            :value="item.name"
            :key="index">{{ item.name }}</Option>
        </Select>
      </FormItem>
      <FormItem label="图层字段：">
        <Select
          v-model="formItem.params2"
          :disabled="formItem.layer2===''?true:false"
          placeholder="请选择图层二"
        >
          <Option
            v-for="(item,index) in layerParams2"
            :value="item.name"
            :key="index">{{ item.name }}</Option>
        </Select>
      </FormItem>
      <FormItem label="分析方式：">
        <Select
          v-model="formItem.type"
          filterable
          @on-change="selectType">
          <Option
            v-for="(item,index) in analysType"
            :value="item.value"
            :key="index">{{ item.label }}</Option>
        </Select>
      </FormItem>
      <FormItem label="绘制方式：">
        <Tooltip
          content="请到第一个地图上绘制范围！"
          placement="top-start"
          transfer>
          <Icon type="information-circled"></Icon>
        </Tooltip>
        <DrawTools
          @on-get-drawlayer="getDrawLayer"></DrawTools>
      </FormItem>
      <FormItem
        label="空间关系："
        prop="spaceRelation">
        <RadioGroup v-model="formItem.spaceRelation">
          <Radio label="intersects">相交</Radio>
          <Radio label="contains">包含</Radio>
        </RadioGroup>
      </FormItem>
      <FormItem>
        <Button
          :loading="analysLoading"
          type="primary"
          size="small"
          @click.native="overLapAnalys">分析</Button>
        <Button
          :disabled="!isAnalys"
          :loading="changesLoading"
          type="primary"
          size="small"
          @click.native="overLapChanges">变化</Button>
        <Button
          :disabled="!isAnalys"
          :loading="folwLoading"
          type="success"
          size="small"
          @click.native="flowAnalysis">流向分析</Button>
    </formitem></Form>
  </div>
</template>
<style lang="less" scoped>
.datav-analys {
  width: 100%;
  height: calc(~'100vh - 120px');

  .k-form {
    width: 90%;
    margin: 0 auto;

    .k-form-item {
      margin-bottom: 7px;
    }
  }

  .k-tooltip {
    position: absolute;
    left: -20px;
  }
}

/deep/ .k-tooltip-inner {
  max-width: 300px;
}
</style>
